<?php


namespace app\admin\controller;


use app\admin\common\library\FlowEngine;
use app\admin\model\ApplyType;
use app\admin\model\Approval;
use app\admin\model\Caigou;
use app\admin\model\Che;
use app\admin\model\Common;
use app\admin\model\FlowInstance;
use app\admin\model\FlowScheme;
use app\admin\model\FlowTask;
use app\admin\model\Money;
use app\admin\model\ProjectBudgetTypeConfig;
use app\admin\model\Scheme;
use app\admin\model\WorkFlows;
use app\admin\model\WorkRun;
use app\admin\model\Zhang;
use app\BaseController;
use think\facade\Db;
use think\facade\View;
use think\Request;
use think\Session;

class Applies extends BaseController
{
    protected $username = "";
    protected $group_id = "";
    protected $group_name = "";
    protected $scheme = null;
    protected $model = null;
    public function initialize()
    {
        parent::initialize();
        //$admin_id = $this->auth->id;
        $username = $this->auth->nickname;
        $this->scheme = new Scheme();
        $group_id = "";
        $group_name = "";
        foreach ($this->auth->getGroups() as $key => $value) {
            $group_id = $value['id'];
            $group_name = $value['name'];
        }
        $apply_type = ApplyType::where('status', 1)->select();
        $this->username = $username;
        $this->group_id = $group_id;
        $this->group_name = $group_name;
        $this->model = new \app\admin\model\Applies();
        View::assign('apply_type', $apply_type);
        View::assign('username', $username);
        View::assign('group_name', $group_name);
        View::assign('time', date('Y-m-d H:s:i', time()));

    }

    //新增
    public function add(Request $request)
    {

        $type_id = $request->param('type_id');
        $cg = Db::name('cg_type')->field('id,name,price')->select();
        $flow = \app\admin\model\Scheme::where('flowname', 'in', ['借款', '用章', '用车', '采购'])->select();
        if ($request->isAjax()) {
            $type_id = $request->param('type_id');
            $params = $request->only(['type_id', 'type_name', 'now_time', 'flow_id']);
            $params['admin_id'] = $this->auth->id;
            $params['username'] = $this->username;
            $params['group_id'] = $this->group_id;
            $params['group_name'] = $this->group_name;
            $params['status'] = 1;
            $result = \app\admin\model\Applies::create($params);
            switch ($type_id){
                case 1: //章
                    $data = $request->only(['name', 'yz_content']);
                    $data['applies_id'] = $result->id;
                    $content = "用章";
                    Zhang::create($data);
                    break;
                case 2: //车

                    $info = $request->only(['start_address', 'plan_lx','start_time','end_time','day','che_dj','che_zongjia','sj_name','sj_phone','ycr']);

                    $data = [];
                    foreach (array_filter($info['start_address']) as $key=>$value){
                        $data[$key]['start_address'] = $value;
                        $data[$key]['plan_lx'] = $info['plan_lx'][$key] ?? '';
                        $data[$key]['start_time'] = $info['start_time'][$key]  ?? '';
                        $data[$key]['end_time'] = $info['end_time'][$key] ?? '';
                        $data[$key]['day'] = $info['day'][$key] ?? '';
                        $data[$key]['che_dj'] = $info['che_dj'][$key] ?? '';
                        $data[$key]['che_zongjia'] = $info['che_zongjia'][$key] ?? '';
                        $data[$key]['sj_name'] = $info['sj_name'][$key] ?? '';
                        $data[$key]['sj_phone'] = $info['sj_phone'][$key] ?? '';
                        $data[$key]['ycr'] = $info['ycr'][$key] ?? '';
                        $data[$key]['applies_id'] = $result->id ?? '';
                    }
                    $content = "用车";
                    $che = new Che();
                    $che->saveAll($data);
                    break;
                case 3: //借款
                    $data = $request->only(['jk_fs', 'jk_money','sk_name','sk_zh','sk_khh','sk_content']);
                    $data['applies_id'] = $result->id;
                    $content = "借款";
                    Money::create($data);
                    break;
                case 4://采购
                    $info = $request->only(['cg_guige', 'cg_num','cg_dj','cg_zongjia','content']);
                    $data = [];
                    foreach (array_filter($info['cg_guige']) as $key=>$value){
                        $data[$key]['cg_guige'] = $value;
                        $data[$key]['cg_num'] = $info['cg_num'][$key];
                        $data[$key]['cg_dj'] = $info['cg_dj'][$key] ?? '';
                        $data[$key]['cg_zongjia'] = $info['cg_zongjia'][$key] ?? '';
                        $data[$key]['content'] = $info['content'][$key];
                        $data[$key]['applies_id'] = $result->id;
                    }
                    $content = "采购";
                    $caigou = new Caigou();
                    $caigou->saveAll($data);
                    break;
                default:
                    $content = "";
                    break;
            }
            if ($result) {
                $scheme = Scheme::find($params['flow_id']);
                $serial_no = $this->getnumber($scheme['flowcode']);
                $this->flow = new FlowEngine($scheme['flowcode']);
                $config = [
                    'instancecode' => $serial_no,
                    'start_time' => $params['now_time'],
                    'content' => $content,
                    'from_id' => $result->id,
                    'from_table' => 'applies'
                ];
                $this->flow->start($config);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
        }
        View::assign('flow', $flow);
        View::assign('cg_type', $cg);
        View::assign('type_id', $type_id);
        return View::fetch("administration/apply/add");
    }
    //编辑
    public function edit(Request $request, $id)
    {

        $flow = \app\admin\model\Scheme::where('flowname', 'in', ['借款', '用章', '用车', '采购'])->select();
        $cg = Db::name('cg_type')->field('id,name,price')->select();
        $apply =$this->model->with(['che','money','cg','zhang'])->find($id);

        if ($request->isAjax()) {
            $params = $request->only(['type_id', 'type_name', 'now_time', 'flow_id']);
            $params['id'] = $id;
            $result = \app\admin\model\Applies::update($params);
            switch ($params['type_id']){
                case 1: //章
                    $data = $request->only(['name', 'yz_content']);
                    $data['applies_id'] = $id;
                    $data['id'] = $request->param('zhang_id');
                    $content = "用章";
                    Zhang::update($data);
                    break;
                case 2: //车
                    $info = $request->only(['start_address', 'plan_lx','start_time','end_time','che_dj','che_zongjia','day','sj_name','sj_phone','ycr']);
                    $data = [];
                    foreach (array_filter($info['start_address']) as $key=>$value){
                            $data[$key]['start_address'] = $value?? '';
                            $data[$key]['plan_lx'] = $info['plan_lx'][$key] ?? '';
                            $data[$key]['start_time'] = $info['start_time'][$key]  ?? '';
                            $data[$key]['end_time'] = $info['end_time'][$key] ?? '';
                            $data[$key]['day'] = $info['day'][$key] ?? '';
                            $data[$key]['che_dj'] = $info['che_dj'][$key] ?? '';
                            $data[$key]['che_zongjia'] = $info['che_zongjia'][$key] ?? '';
                            $data[$key]['sj_name'] = $info['sj_name'][$key] ?? '';
                            $data[$key]['sj_phone'] = $info['sj_phone'][$key] ?? '';
                            $data[$key]['ycr'] = $info['ycr'][$key] ?? '';
                            $data[$key]['applies_id'] = $id ?? '';
                    }
                     $che = new Che();
                    if ($data) {
                        $res_del = Che::destroy(function ($query) use ($id) {
                            $query->where('applies_id', $id);
                        },true); //先强制删除
                        if ($res_del) {
                            $che->saveAll($data); //在新增
                        }
                    }
                    break;
                case 3: //借款
                    $data = $request->only(['jk_fs', 'jk_money','sk_name','sk_zh','sk_khh','sk_content']);
                    $data['applies_id'] = $id;
                    $data['id'] = $request->param('jk_id');
                    $content = "借款";
                    Money::update($data);
                    break;
                case 4://采购
                    $info = $request->only(['cg_guige', 'cg_num','cg_dj','cg_zongjia','content']);

                    $data = [];
                    foreach (array_filter($info['cg_guige']) as $key=>$value){
                        if ($info['cg_num'][$key] !== "" &&  $info['cg_dj'][$key] !== "" && $info['cg_zongjia'][$key] !== ""){
                            $data[$key]['cg_guige'] = $value;
                            $data[$key]['cg_num'] = $info['cg_num'][$key];
                            $data[$key]['cg_dj'] = $info['cg_dj'][$key] ?? '';
                            $data[$key]['cg_zongjia'] = $info['cg_zongjia'][$key] ?? '';
                            $data[$key]['content'] = $info['content'][$key];
                            $data[$key]['applies_id'] = $id;
                        }
                    }
                    $content = "采购";
                    $caigou = new Caigou();
                    if ($data) {
                        $res_del = Caigou::destroy(function ($query) use ($id) {
                            $query->where('applies_id', $id);
                        },true); //先强制删除
                        if ($res_del) {
                            $caigou->saveAll($data); //在新增
                        }
                    }
//                    $caigou->saveAll($data);
                    break;
                default:
                    $content = "";
                    break;
            }
            if ($result) {
//                $scheme = Scheme::find($params['flow_id']);
//                $serial_no = $this->getnumber($scheme['flowcode']);
//                $this->flow = new FlowEngine($scheme['flowcode']);
//                $config = [
//                    'instancecode' => $serial_no,
//                    'start_time' => $params['now_time'],
//                    'content' => $params['content'],
//                    'from_id' => $params['id'],
//                    'from_table' => 'applies'
//                ];
//                $this->flow->start($config);
                return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
            }
        }
        View::assign('flow', $flow);
        View::assign('cg_type', $cg);
        View::assign('model', $apply);
        return View::fetch("administration/apply/edit");
    }
    //编辑并提交
    public function editsbumit(Request $request, $id)
    {
        $flow = \app\admin\model\Scheme::where('flowname', 'in', ['借款', '用章', '用车', '采购'])->select();
        $apply =$this->model->with(['che','money','cg','zhang'])->find($id);
        if ($request->isAjax()) {
            $qita = $request->param('qita');
            $params = $request->only(['type_id', 'type_name', 'now_time', 'flow_id']);
            $params['status'] = 1;//流程中
            $result = \app\admin\model\Applies::update($params);

            switch ($params['type_id']){
                case 1: //章
                    $data = $request->only(['name', 'yz_content']);
                    $data['applies_id'] = $id;
                    $data['id'] = $request->param('zhang_id');
                    $content = "用章";
                    Zhang::update($data);
                    break;
                case 2: //车
                    $info = $request->only(['start_address', 'plan_lx','start_time','end_time','day','sj_name','sj_phone','ycr']);
                    $data = [];
                    foreach (array_filter($info['start_address']) as $key=>$value){
                        $data[$key]['start_address'] = $value?? '';
                        $data[$key]['plan_lx'] = $info['plan_lx'][$key] ?? '';
                        $data[$key]['start_time'] = $info['start_time'][$key]  ?? '';
                        $data[$key]['end_time'] = $info['end_time'][$key] ?? '';
                        $data[$key]['day'] = $info['day'][$key] ?? '';
                        $data[$key]['sj_name'] = $info['sj_name'][$key] ?? '';
                        $data[$key]['sj_phone'] = $info['sj_phone'][$key] ?? '';
                        $data[$key]['ycr'] = $info['ycr'][$key] ?? '';
                        $data[$key]['applies_id'] = $id ?? '';
                    }
                    $che = new Che();
                    if ($data) {
                        $res_del = Che::destroy(function ($query) use ($id) {
                            $query->where('applies_id', $id);
                        },true); //先强制删除
                        if ($res_del) {
                            $che->saveAll($data); //在新增
                        }
                    }
                    break;
                case 3: //借款
                    $data = $request->only(['jk_fs', 'jk_money','sk_name','sk_zh','sk_khh','sk_content']);
                    $data['applies_id'] = $id;
                    $data['id'] = $request->param('jk_id');
                    $content = "借款";
                    Money::update($data);
                    break;
                case 4://采购
                    $info = $request->only(['cg_guige', 'cg_num','content']);
                    $data = [];
                    foreach (array_filter($info['cg_guige']) as $key=>$value){
                        $data[$key]['cg_guige'] = $value;
                        $data[$key]['cg_num'] = $info['cg_num'][$key];
                        $data[$key]['content'] = $info['content'][$key];
                        $data[$key]['applies_id'] = $id;
                    }
                    $content = "采购";
                    $caigou = new Caigou();
                    if ($data) {
                        $res_del = Caigou::destroy(function ($query) use ($id) {
                            $query->where('applies_id', $id);
                        },true); //先强制删除
                        if ($res_del) {
                            $caigou->saveAll($data); //在新增
                        }
                    }
//                    $caigou->saveAll($data);
                    break;
                default:
                    $content = "";
                    break;
            }
            if ($result) {
                $task = FlowTask::where([
                    'receiveid' => $this->auth->id,
                    'from_id' => $id,
                    'from_table' => 'applies',
                    'status' => '0'
                ])->find(); //找到当前任务流程
                $res = Db::name('view_workitem')->where([
                    'receiveid' => $this->auth->id,
                    'from_id' => $id,
                    'from_table' => 'applies',
                    'status' => '0'
                ])->find(); //找到当前任务视图
                $schme = $this->scheme->find($task['flowid']);
                $this->flow = new FlowEngine($schme['flowcode']);
                $row = Db::name($res['bizscheme'])->find($res['bizobjectid']);
                $this->flow->next($res['id'], $row, '[拒绝后提交]');
                return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
            }
        }
        View::assign('flow', $flow);
        View::assign('model', $apply);
        return View::fetch("administration/apply/editsubmit");
    }

    //删除
    public function del($ids = "")
    {

        if ($ids) {
            $ids = explode(',', $ids);
            foreach ($ids as $key => $value) {
                $task = FlowTask::where(['from_id' => $value, 'from_table' => 'applies'])->select();
                $task->delete();
                \app\admin\model\Applies::destroy($value);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
        }
    }


    //类别读取
    public function type(Request $request)
    {
        $id = $request->param('id');
        if ($id == 1) {
            $model = \app\admin\model\Applies::$chapter;
        } else if ($id == 2) {
            $model = \app\admin\model\Applies::$car;
        } else if ($id == 3) {
            $model = \app\admin\model\Applies::$money;
        } else if ($id == 4) {
            $model = \app\admin\model\Applies::$purchase;
        } else {
            $model = "";
        }
        return json_encode($model);
    }

    //电子签名
    public function signature(Request $request)
    {
        $id = $request->param('id');
        $content = $request->param('content');
        $type = $request->param('type');
        if ($request->isAjax()) {
            $data = $request->only(['path', 'applies_id']);
            $data['content'] = trim($request->param('content'));
            $data['username'] = $this->username;
            $data['group_name'] = $this->group_name;
            if (strpos($request->param('type'), '不通过') !== false) {
                $data['status'] = 1; //终止审批
                $status = 1;
            } else if ($this->auth->isSuperAdmin($this->auth->id) === true) { //判断是不是最终超级管理员审批
                $data['status'] = 1; //审批完成
                $status = 1;
            } else {
                $status = 0;
            }
            $data['remarks'] = $this->group_name . '[' . $this->username . ']:审批' . $request->param('type') . ',审批时间为:' . date('Y-m-d H:i:s', time());


            $result = WorkFlows::create($data);
            if ($result) {
                \app\admin\model\Applies::update(['status' => $status, 'id' => $request->param('applies_id')]);
                return json(['code' => 200, 'url' => '', 'msg' => '感谢您的审批！']);
            }
        }
        View::assign('id', $id);
        View::assign('content', $content);
        View::assign('type', $type);
        return View::fetch("administration/apply/signature");
    }

    //读取
    public function record($id)
    {
        $work_flows = WorkFlows::where('applies_id', $id)->select();
        foreach ($work_flows as $key => $flow) {
            $work_flows[$key]['new_path'] = 'data:' . $flow['path'];
        }
        View::assign('work_flow', $work_flows);
        return View::fetch("administration/apply/record");
    }


    //部门审核
    public function sh(Request $request)
    {
        $flow = FlowScheme::select();
        $id = $request->param('id');
        $model = Approval::with(['admin' => ['AuthGroups'], 'typeName'])->find($id);
        $item = empty($model) ? array() : $model->toArray();
        $res = WorkRun::searchTable($item['from_table'], $item['from_id']);
        $item['group_name'] = $item['admin']['AuthGroups']['name'] ?? "unknown";
        $item['username'] = $item['admin']['nickname'] ?? $item['admin']['username'];
        $item['status_table'] = $res['status'] ?? 1;
        $item['type_name'] = $item['typeName']['name'] ?? "休假";
        $item['content'] = $res['shiyou'] ?? '';
        $item['res'] = $res;
        if ($request->isAjax()) {
            $res_update = Approval::update([
                'id' => $id,
                'status' => 1
            ]);
            if ($res_update) {
                $config = [
                    'wf_id' => $request->param('flow_id'),
                    'wf_fid' => $item['from_id'],
                    'wf_type' => $item['from_table'], //表名称
                ];
                $this->work->startworkflow($config, $this->auth->id);
                return json(['code' => 200, 'url' => '', 'msg' => '感谢您的审批！']);
            }
        }
        View::assign('flow', $flow);
        View::assign('model', $item);
        return View::fetch('administration/apply/sh');
    }


    //查看详情
    public function sh_detail(Request $request)
    {
        $from_id = $request->param('from_id');

        $from_table = $request->param('from_table');

        $item = \app\admin\model\Applies::checkDetail($from_table, $from_id);

//        $model = Approval::where(['from_id'=>$from_id,'from_table'=>$from_table])->with(['admin' => ['AuthGroups'], 'typeName'])->find();
//        $item = empty($model) ? array() : $model->toArray();
//        $res = WorkRun::searchTable($item['from_table'], $item['from_id']);
//        $item['group_name'] = $item['admin']['AuthGroups']['name'] ?? "unknown";
//        $item['username'] = $item['admin']['nickname'] ?? $item['admin']['username'];
//        $item['status_table'] = $res['status'] ?? 1;
//        $item['type_name'] = $item['typeName']['name'] ?? "休假";
//        $item['res'] = $res;
        View::assign('model', $item);
        return View::fetch('administration/apply/sh_detail');
    }


    //查看审核通过后的详情
    public function detail(Request $request)
    {
        $id = $request->param('id');;
        $model = \app\admin\model\Applies::with('typeName')->find($id);
        if($model->typeName->name == "借款"){
            $money = Db::name('applies_money')->where('applies_id',$id)->find();
            $d = FlowTask::field('id,instanceid,flowid,from_id,from_table')->where(['from_id'=>$id,'from_table'=>'applies'])->find();
            $semd = Scheme::find($d['flowid']);
            $ds = FlowInstance::find($d->instanceid);
            $money['dx'] = get_amount($money['jk_money']);
            $model['money'] = $money;
            $model['ids'] = $ds->bizobjectid;
            $model['ids_table'] = $semd->bizscheme;
            $model['ids_code'] = $semd->flowcode;
            $model['task_id'] = $d->id;
        }else if ($model->typeName->name == "用章"){
            $zhang = Db::name('applies_zhang')->where('applies_id',$id)->find();
            $model['zhang'] = $zhang;
        }else if ($model->typeName->name == "用车"){
            $che = Db::name('applies_che')->where('applies_id',$id)->select();
            $model['che'] = $che;
        }else if ($model->typeName->name == "采购"){
            $caigou = Db::name('applies_cg')->where('applies_id',$id)->select();
            $model['caigou'] = $caigou;
        }else{
            $model="";
        }
        $src = "detail/applies_detail";
        $table = 'applies';
        $common = new \app\admin\model\Common($id, $table);
        $data = $common->getCheckFlow();
        View::assign('model', $model);
        View::assign("history", $data['history']);
        return View::fetch("administration/apply/detail");


    }
}
